package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.BaiDuProperties;
import com.sky.result.BaiDistanceDuresult;
import com.sky.result.BaiDuResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chengjy
 * @date 2023/4/26
 */
//百度地图工具类
@Component
public class BaiDuUtil {

    @Autowired
    private BaiDuProperties baiDuProperties;
    /**
     * 根据收货地址返回该地址经纬度
     * @param address
     * @return--经纬度
     */
    public String getLocation(String address){

        HttpClientUtil http = new HttpClientUtil();
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("address",address);
        paramMap.put("ak",baiDuProperties.getKey());
        paramMap.put("output","json");
        //发送请求
        String json = http.doGet(baiDuProperties.getGeocodingUrl(), paramMap);
        //转换返回值格式
        JSONObject jsonObject = JSON.parseObject(json);
        String status =  jsonObject.getString("status");
        String result =  jsonObject.getString("result");
        BaiDuResult baiDuResult = JSON.parseObject(result, BaiDuResult.class);
        Map<String, String> locationMap = baiDuResult.getLocation();
        System.err.println("地名："+address+" 请求响应："+status+" 经纬度："+locationMap);
        //经纬度
        String location = locationMap.get("lat")+","+locationMap.get("lng");
        return location;
    }

    /**
     * 计算两地经纬度距离
     * @param a,b：地名
     * @return
     */
    public Integer getDistances(String a,String b){
       /* //北京
        String a = "40.05682848596073,116.3076223267197";
        //长沙
        String b = "28.221846282292675,112.86865450986194";*/
        HttpClientUtil http = new HttpClientUtil();
        Map<String,String> paramMap = new HashMap<>();
        //填充属性
        paramMap.put("origin",a);
        paramMap.put("destination",b);
        paramMap.put("ak",baiDuProperties.getKey());
        String json = http.doGet(baiDuProperties.getDrivingUrl(), paramMap);
        //获取返回内容
        JSONObject jsonObject = JSON.parseObject(json);
        String resutl =  jsonObject.getString("result");
        BaiDistanceDuresult resultDTO = JSON.parseObject(resutl, BaiDistanceDuresult.class);
        //获取距离
        Integer distances = resultDTO.getRoutes().get("distance");
        return distances/1000;
    }
}
